package cn.tedu.dbinit;

import com.sun.org.apache.bcel.internal.util.ClassPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {

    //注入数据源
    @Autowired
    private DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(DbInitApplication.class, args);
    }

    @PostConstruct //创建完所有的实例 ,并且执行完所有的依赖注入之后自动执行；
    public void  init() throws SQLException {

       exec("sql/account.sql");
       exec("sql/order.sql");
       exec("sql/seata-server.sql");
       exec("sql/storage.sql");

    }

    private void exec(String file) throws SQLException {

        //封装资源对象
        ClassPathResource cpr = new ClassPathResource(file, DbInitApplication.class.getClassLoader());
        //编码的资源对象
        EncodedResource resource = new EncodedResource(cpr);
        ScriptUtils.executeSqlScript(dataSource.getConnection(),resource);
    }

}
